#include <QTextStream>
#include <QMessageBox>
#include <QDebug>
#include <QFileInfo>

#include "defines.h"
#include "generatorfileoutput.h"

GeneratorFileOutput::GeneratorFileOutput(const QString& outputFile)
	: m_outputFile(0)
{
	setOutput(outputFile);
}

GeneratorFileOutput::~GeneratorFileOutput()
{
	if (m_outputFile)
	{
		m_outputFile->close();
	}
	delete m_outputFile;
}

bool GeneratorFileOutput::setOutput(const QString &outputFile)
{
	// Check if the new file is the same as the old one
	if (!m_outputFile || QFileInfo(outputFile) != QFileInfo(*m_outputFile))
	{
		if (m_outputFile)
		{
			m_outputFile->close();
		}
		delete m_outputFile;
		m_outputFile = 0;

		m_outputFile = new QFile(outputFile);
		if (!m_outputFile->open(QIODevice::WriteOnly | QIODevice::Text))
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		return true;
	}
}

void GeneratorFileOutput::printOutput(const QString &message)
{
	if (m_outputFile)
	{
		qDebug() << message;
		QTextStream(m_outputFile) << message << "\n";
	}

	emit GeneratorOutputView::message(message);
}
